package pub.tbc.rubbish.client.registry.impl;

import pub.tbc.rubbish.client.Constant;
import pub.tbc.rubbish.client.registry.Registry;
import pub.tbc.rubbish.client.util.RedisHelper;
import pub.tbc.toolkit.PropsUtil;
import redis.clients.jedis.Jedis;

import java.util.concurrent.TimeUnit;

/**
 * @author tbc on 2016/12/7 14:59:39.
 */
public class RedisRegistry implements Registry {
    private Jedis client = getRedisClient();

    private final String SERVICE_SEPARATOR = "::";

    @Override
    public void register(String serviceName, String serviceAddress) {

        String serviceNode = getRegistryNode() + serviceName;
        // 先设置一个set-> serviceName : {ip:port,ip:port...}
        client.sadd(serviceNode, serviceAddress);
        // 发布消息
        client.publish(serviceName, serviceNode);
    }

    private String getRegistryNode() {
        return PropsUtil.getString(
                PropsUtil.load(Constant.DEFAULT_CONFIG_FILE),
                Constant.REGISTRY_NODE,
                "rubbish.registry."
        );
    }

    private Jedis getRedisClient() {
        return RedisHelper.getClientFromPool();
    }

    /**
     * 定时任务，维持心跳
     */
    private void pingPong() {
        int failCount = 0;
        while (true) {
            try {
                TimeUnit.SECONDS.sleep(5);
            } catch (InterruptedException e) {
                throw new RuntimeException(e.getMessage(), e);
            }

            if ("PONG".equals(client.ping())) {
                continue;
            }

            failCount++;
        }
    }
}
